package com.vegetable.modules.service.stock.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vegetable.modules.entity.stock.PriceAlertRecord;
import com.vegetable.modules.mapper.stock.PriceAlertRecordMapper;
import com.vegetable.modules.service.stock.IPriceAlertRecordService;
import com.vegetable.modules.mapper.stock.PriceAlertRecordQueryMapper;
import com.vegetable.modules.entity.dashboard.PriceAlertVO;
import com.vegetable.modules.entity.stock.po.PriceAlertRecordQueryPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 价格预警记录表 服务实现类
 * </p>
 *
 * @author qoder
 * @since 2025-09-11
 */
@Slf4j
@Service
public class PriceAlertRecordServiceImpl extends ServiceImpl<PriceAlertRecordMapper, PriceAlertRecord> implements IPriceAlertRecordService {

    @Autowired
    private PriceAlertRecordQueryMapper priceAlertRecordQueryMapper;

    /**
     * 通过实时查询获取价格预警记录列表，而不是从数据库中获取
     */
    public Page<PriceAlertRecord> page(Page<PriceAlertRecord> page, PriceAlertRecordQueryPO po) {
        // 获取所有实时价格预警数据，根据分页参数获取相应数量
        // 如果没有传入orderTime参数，则默认使用当前日期
        Date orderTime = po.getOrderTime() != null ? po.getOrderTime() : new Date();
        List<PriceAlertVO> priceAlertVOs = priceAlertRecordQueryMapper.getPriceAlerts(null, orderTime);
        
        // 应用价格差异阈值过滤条件
        List<PriceAlertVO> filteredVOs = priceAlertVOs.stream()
                .filter(vo -> vo.getPriceDifference() != null && 
                             vo.getAlertThreshold() != null && 
                             vo.getPriceDifference().compareTo(vo.getAlertThreshold()) >= 0)
                .collect(Collectors.toList());
        
        // 转换为PriceAlertRecord对象
        List<PriceAlertRecord> records = filteredVOs.stream().map(vo -> {
            PriceAlertRecord record = new PriceAlertRecord();
            record.setCommodityId(vo.getCommodityId());
            record.setCommodityCode(vo.getCommodityCode());
            record.setStandard(vo.getStandard());
            record.setCommodityName(vo.getCommodityName());
            record.setTodayMinPrice(vo.getTodayMinPrice());
            record.setTodayMaxPrice(vo.getTodayMaxPrice());
            record.setPriceDifference(vo.getPriceDifference());
            record.setAlertThreshold(vo.getAlertThreshold());
            record.setAlertLevel(vo.getAlertLevel());
            // 设置订单ID
            record.setMinPriceOrderId(vo.getMinPriceOrderId());
            record.setMaxPriceOrderId(vo.getMaxPriceOrderId());
            // 设置分类信息
            record.setCategoryId(vo.getCategoryId());
            record.setCategoryName(vo.getCategoryName());
            // 默认设置为未处理状态
            record.setAlertStatus(0);
            return record;
        }).collect(Collectors.toList());
        
        // 应用查询条件
        List<PriceAlertRecord> finalRecords = records;
        
        // 商品名称模糊查询
        if (po.getCommodityNameLike() != null && !po.getCommodityNameLike().isEmpty()) {
            finalRecords = finalRecords.stream()
                    .filter(record -> record.getCommodityName() != null && 
                            record.getCommodityName().contains(po.getCommodityNameLike()))
                    .collect(Collectors.toList());
        }
        
        // 预警状态查询
        if (po.getAlertStatus() != null) {
            finalRecords = finalRecords.stream()
                    .filter(record -> record.getAlertStatus() != null && 
                            record.getAlertStatus().equals(po.getAlertStatus()))
                    .collect(Collectors.toList());
        }
        
        // 商品分类ID查询
        if (po.getCategoryId() != null) {
            finalRecords = finalRecords.stream()
                    .filter(record -> record.getCategoryId() != null && 
                            record.getCategoryId().equals(po.getCategoryId()))
                    .collect(Collectors.toList());
        }
        
        // 分页处理
        long total = finalRecords.size();
        long offset = (page.getCurrent() - 1) * page.getSize();
        long end = Math.min(offset + page.getSize(), total);
        
        List<PriceAlertRecord> pagedRecords = total > 0 ? finalRecords.subList((int) offset, (int) end) : new ArrayList<>();
        page.setRecords(pagedRecords);
        page.setTotal(total);
        
        return page;
    }

    /**
     * 通过实时查询获取未处理价格预警记录数量
     */
    public int count(PriceAlertRecordQueryPO po) {
        // 获取所有实时价格预警数据，获取全部数据而不是限制25条
        // 如果没有传入orderTime参数，则默认使用当前日期
        Date orderTime = po.getOrderTime() != null ? po.getOrderTime() : new Date();
        List<PriceAlertVO> priceAlertVOs = priceAlertRecordQueryMapper.getPriceAlerts(null, orderTime);
        
        // 应用价格差异阈值过滤条件
        List<PriceAlertVO> filteredVOs = priceAlertVOs.stream()
                .filter(vo -> vo.getPriceDifference() != null && 
                             vo.getAlertThreshold() != null && 
                             vo.getPriceDifference().compareTo(vo.getAlertThreshold()) >= 0)
                .collect(Collectors.toList());
        
        // 转换为PriceAlertRecord对象并过滤未处理的记录
        List<PriceAlertRecord> records = filteredVOs.stream().map(vo -> {
            PriceAlertRecord record = new PriceAlertRecord();
            record.setCommodityId(vo.getCommodityId());
            record.setCommodityName(vo.getCommodityName());
            record.setTodayMinPrice(vo.getTodayMinPrice());
            record.setTodayMaxPrice(vo.getTodayMaxPrice());
            record.setPriceDifference(vo.getPriceDifference());
            record.setAlertThreshold(vo.getAlertThreshold());
            record.setAlertLevel(vo.getAlertLevel());
            // 设置订单ID
            record.setMinPriceOrderId(vo.getMinPriceOrderId());
            record.setMaxPriceOrderId(vo.getMaxPriceOrderId());
            // 设置分类信息
            record.setCategoryId(vo.getCategoryId());
            record.setCategoryName(vo.getCategoryName());
            // 默认设置为未处理状态
            record.setAlertStatus(0);
            return record;
        }).collect(Collectors.toList());
        
        // 预警状态查询
        if (po.getAlertStatus() != null) {
            records = records.stream()
                    .filter(record -> record.getAlertStatus() != null && 
                            record.getAlertStatus().equals(po.getAlertStatus()))
                    .collect(Collectors.toList());
        }
        
        // 商品分类ID查询
        if (po.getCategoryId() != null) {
            records = records.stream()
                    .filter(record -> record.getCategoryId() != null && 
                            record.getCategoryId().equals(po.getCategoryId()))
                    .collect(Collectors.toList());
        }
        
        return records.size();
    }
    
    /**
     * 重载方法，保持与父类接口兼容
     */
    @Override
    public Page<PriceAlertRecord> page(Page<PriceAlertRecord> page, QueryWrapper<PriceAlertRecord> queryWrapper) {
        // 创建一个空的PO对象
        PriceAlertRecordQueryPO po = new PriceAlertRecordQueryPO();
        return page(page, po);
    }
    
    /**
     * 重载方法，保持与父类接口兼容
     */
    @Override
    public int count(QueryWrapper<PriceAlertRecord> queryWrapper) {
        // 创建一个空的PO对象
        PriceAlertRecordQueryPO po = new PriceAlertRecordQueryPO();
        return count(po);
    }
}